package com.zl.roomdesign.main.mainpage

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.zl.core.MainApp
import com.zl.core.api.ServiceGenerator
import com.zl.core.api.data.BaseResult
import com.zl.core.base.ModeFragment
import com.zl.core.utils.FileUtils
import com.zl.core.view.StickerView
import com.zl.roomdesign.R
import com.zl.roomdesign.main.ImageListActivity
import com.zl.roomdesign.main.MainApi
import com.zl.roomdesign.main.MaterialEntity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_main_page.*
import kotlinx.android.synthetic.main.item_text_img.view.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


/**
 * Created by zhangli on 2018/5/6,13:29<br/>
 */
class MainPageFragment : ModeFragment() {

    private val api = ServiceGenerator.createRxService(MainApi::class.java)

    private val list = mutableListOf<MaterialEntity>()
    private lateinit var mAdapter: MaterialAdapter

    private val materialList = mutableListOf<MaterialEntity>()

    override fun layoutId() = R.layout.fragment_main_page

    override fun initView(savedInstanceState: Bundle?) {

        mAdapter = MaterialAdapter(list, {
            val mutableList = list[it.adapterPosition].list
            if (mutableList != null) {
                list.clear()
                list.addAll(mutableList)
                mAdapter.notifyDataSetChanged()
                returnImg.visibility = View.VISIBLE
            } else {
                if ("平面图" == list[it.adapterPosition].type) {
                    val simpleTarget = object : SimpleTarget<Drawable>() {
                        override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>) {
                            containerLayout.background = resource
                        }
                    }
                    Glide.with(this).load(MainApp.instance.serverUrl + list[it.adapterPosition].fileName).into(simpleTarget);
                } else {
                    editPhoto(it)
                }
            }
        })
        recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        recyclerView.adapter = mAdapter

    }

    private fun editPhoto(viewHolder: MaterialAdapter.ViewHolder) {
        val bitmap = (viewHolder.itemView.img.drawable as? BitmapDrawable)?.bitmap
        if (bitmap != null) {

            val view = StickerView(activity, bitmap)

            val params = RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
            params.addRule(RelativeLayout.CENTER_IN_PARENT)
            view.setLayoutParams(params)
            containerLayout.addView(view)
        }
    }

    override fun setListener() {

        cancelImg.setOnClickListener {
            containerLayout.removeAllViews()
            containerLayout.background = null
        }

        doneImg.setOnClickListener {
            val bitmap = loadBitmapFromView(containerLayout)
            if (bitmap != null) {
                val image = ImageView(activity)
                image.setImageBitmap(bitmap)
                AlertDialog.Builder(activity)
                        .setTitle("作品")
                        .setView(image)
                        .setPositiveButton("上传", { _, _ ->
                            upload(bitmap)
                        })
                        .setNegativeButton("取消", null)
                        .show()
            } else {
                showToast("bitmap null")
            }
        }

        returnImg.setOnClickListener {
            list.clear()
            list.addAll(materialList)
            mAdapter.notifyDataSetChanged()
            returnImg.visibility = View.GONE
        }

        titleText.setOnClickListener {
            AlertDialog.Builder(activity!!)
                    .setItems(arrayOf("刷新服务器素材", "仅获取服务器素材", "上传素材"), { _, which ->
                        when (which) {
                            0 -> {
                                getMaterial(api.refresh())
                            }
                            1 -> {
                                getMaterial(api.getMaterial())
                            }
                            2 -> {
                                startActivity(Intent(activity, ImageListActivity::class.java))
                            }
                        }
                    })
                    .show()

        }
    }

    @SuppressLint("MissingPermission")
    private fun upload(bitmap: Bitmap) {
        val name = System.currentTimeMillis().toString() + ".jpg"
        val f = FileUtils.saveMyBitmap(bitmap, name)
        if (f != null) {
            val requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), File(f))
            val part = MultipartBody.Part.createFormData("file", name, requestFile)
            api.upload(part, mapOf(Pair("userName", MainApp.instance.user?.name
                    ?: "unknown"), Pair("phone", MainApp.instance.user!!.phone.toString())))
                    .map {
                        if (it.code == 0) {
                            return@map it.data
                        } else {
                            throw RuntimeException("error:" + it.message)
                        }
                    }
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe {
                        showLoading()
                    }
                    .doOnTerminate {
                        hideLoading()
                    }
                    .subscribe({
                        showToast("上传成功")
                    }, {
                        showToast(it.message + "")
                    })

        }
    }

    override fun observe() {
    }

    override fun afterView() {
//        list.add(R.drawable.a3)
//        list.add(R.drawable.a2)
//        list.add(R.drawable.a4)
//        list.add(R.drawable.a5)
//        list.add(R.drawable.a6)
//        list.add(R.drawable.a7)
//        list.add(R.drawable.a8)
//        list.add(R.drawable.b1)
//        list.add(R.drawable.b2)
//        list.add(R.drawable.b3)
//        list.add(R.drawable.b4)
//        mAdapter.notifyDataSetChanged()

        getMaterial(api.getMaterial())
    }

    private fun getMaterial(material: Observable<BaseResult<MutableList<MaterialEntity>>>) {

        material.map {
            if (it.code == 0) {
                return@map it.data
            } else {
                throw RuntimeException("error" + it.message)
            }
        }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    materialList.clear()
                    if (it != null) {
                        materialList.addAll(it)
                    }

                    list.clear()
                    list.addAll(materialList)
                    mAdapter.notifyDataSetChanged()
                }, {
                    showToast(it.message + "")
                })
    }

    private fun loadBitmapFromView(view: View): Bitmap? {
        view.setDrawingCacheEnabled(true)
        view.buildDrawingCache()  //启用DrawingCache并创建位图
        val bitmap = Bitmap.createBitmap(view.getDrawingCache()) //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
        view.setDrawingCacheEnabled(false)  //禁用DrawingCahce否则会影响性能
        return bitmap
    }

}